package com.owen.java.demo.jexl;

import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.apache.commons.jexl3.internal.Engine;

import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class DymethodUtil {

    public static Object invokeMethod(String jexlExp, Map<String,Object> map){
        JexlEngine jexlEngine=new Engine();
        JexlExpression expression=jexlEngine.createExpression(jexlExp);
        JexlContext jexlContext=new MapContext();
        for (String key:map.keySet()){
            jexlContext.set(key,map.get(key));
        }
        Object result = expression.evaluate(jexlContext);
        if(Objects.isNull(result)){
            return null;
        }
        return result;
    }

    public static void main(String[] args) {
//        Map<String,Object> map=new HashMap<>();
//        PrintStream out = System.out;
//        map.put("out",out);
//        map.put("test","test");
//        String expression="out.println(test)";
//        Object o = invokeMethod(expression, map);

        String expression="import java.util.Date;Date date=new Date();System.out.println(date);";
        invokeMethod(expression,new HashMap<>());

    }

}
